﻿;/*
file:        data-widget.js
author:      loogn
date :       2016-10-1
descript:    DataGrid、Select、Pager
*/

var dw = (function () {
    var dw = {};

    //根据url缓存 ，没有的话要同步获取
    dw.cache = {};
    dw.getCache = function (url) {
        var key = url.toLowerCase();
        var data = dw.cache[key];
        if (data) return data;
        $.ajax({
            url: url,
            type: 'POST',
            async: false,
            success: function (result) {
                dw.cache[key] = result;
                data = result;
            }
        });
        return data;
    }


    var styleArr = [];
    //pager.css
    styleArr.push('table .page a{ text-decoration:none; font-weight:normal;}');
    styleArr.push('table .page span{ text-decoration:none; font-weight:normal;}');
    styleArr.push('table .page a:hover{ text-decoration:none;}');
    styleArr.push('table .page{padding: 15px 20px;text-align: left;color: #ccc;}');
    styleArr.push('table .page a{display: inline-block;color: #428bca;display: inline-block;height: 25px;	line-height: 25px;	padding: 0 10px;border: 1px solid #ddd;	margin: 0 2px;border-radius: 4px;vertical-align: middle;}');
    styleArr.push('table .page span.current{display: inline-block;height: 25px;line-height: 25px;padding: 0 10px;margin: 0 2px;color: #fff;background-color: #428bca;	border: 1px solid #428bca;border-radius: 4px;vertical-align: middle;}');
    styleArr.push('table .page a:hover{text-decoration: none;border: 1px solid #428bca;}');
    styleArr.push('table .page span.disabled{	display: inline-block;height: 25px;line-height: 25px;padding: 0 10px;margin: 0 2px;	color: #bfbfbf;background: #f2f2f2;border: 1px solid #bfbfbf;border-radius: 4px;vertical-align: middle;}');

    var style = $('<style>').text(styleArr.join(''));
    $('head').append(style);


    //dateFormat(new Date(),'yyyy-MM-dd hh:mm:ss')
    dw.dateFormat = function (date, format) {
        var o = {
            "M+": date.getMonth() + 1, //month
            "d+": date.getDate(), //day
            "h+": date.getHours(), //hour
            "m+": date.getMinutes(), //minute
            "s+": date.getSeconds(), //second
            "q+": Math.floor((date.getMonth() + 3) / 3), //quarter
            "S": date.getMilliseconds() //millisecond
        }
        if (/(y+)/.test(format)) {
            format = format.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
        }
        for (var k in o) {
            if (new RegExp("(" + k + ")").test(format)) {
                format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
            }
        }
        return format;
    }

    //得到指定url参数
    dw.getQueryString = function (name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", 'i');
        var r = window.location.search.substr(1).match(reg);
        if (r !== null)
            return unescape(decodeURIComponent(r[2]));
        return null;
    };

    //得到所有url参数对象
    dw.getQueryObject = function () {
        var args = {};
        var query = location.search.substring(1);
        var pairs = query.split("&");
        for (var i = 0; i < pairs.length; i++) {
            var pos = pairs[i].indexOf('=');
            if (pos == -1) continue;
            var name = pairs[i].substring(0, pos);
            var value = pairs[i].substring(pos + 1);
            value = decodeURIComponent(value);
            args[name.toLowerCase()] = value;
        }
        return args;
    };

    return dw;
}());

(function (dwName, dw) {
    function Pager($wrap, pageCount, current, onPageChange) {

        this.$wrap = $wrap;
        this.pageCount = pageCount;
        this.current = current || 1;
        this.onPageChange = onPageChange || function () { };
        this.bindEvent();
        this.render(pageCount, current);

    }

    Pager.prototype.render = function (pageCount, current) {

        this.pageCount = pageCount;
        this.current = current;
        if (pageCount <= 1) {
            this.$wrap.empty();
            return;
        }

        //上一页
        var htmlArr = [];
        if (current > 1) {
            htmlArr.push('<a href="javascript:;" class="prevPage">上一页</a>');
        } else {

            htmlArr.push('<span class="disabled">上一页</span>');
        }
        //中间页码
        if (current != 1 && current >= 4 && pageCount != 4) {
            htmlArr.push('<a href="javascript:;" class="tcdNumber">' + 1 + '</a>');
        }
        if (current - 2 > 2 && current <= pageCount && pageCount > 5) {
            htmlArr.push('<span>...</span>');
        }
        var start = current - 2, end = current + 2;
        if ((start > 1 && current < 4) || current == 1) {
            end++;
        }
        if (current > pageCount - 4 && current >= pageCount) {
            start--;
        }
        for (; start <= end; start++) {
            if (start <= pageCount && start >= 1) {
                if (start != current) {
                    htmlArr.push('<a href="javascript:;" class="tcdNumber">' + start + '</a>');
                } else {
                    htmlArr.push('<span class="current">' + start + '</span>');
                }
            }
        }
        if (current + 2 < pageCount - 1 && current >= 1 && pageCount > 5) {
            htmlArr.push('<span>...</span>');
        }
        if (current != pageCount && current < pageCount - 2 && pageCount != 4) {
            htmlArr.push('<a href="javascript:;" class="tcdNumber">' + pageCount + '</a>');
        }
        //下一页
        if (current < pageCount) {
            htmlArr.push('<a href="javascript:;" class="nextPage">下一页</a>');
        } else {
            this.$wrap.remove('.nextPage');
            htmlArr.push('<span class="disabled">下一页</span>');
        }
        //修改表现
        this.$wrap.html(htmlArr.join(''));
    }

    Pager.prototype.bindEvent = function () {
        var pager = this;
        this.$wrap.on("click", "a.tcdNumber", function () {
            var current = parseInt($(this).text());
            pager.render(pager.pageCount, current);
            if (typeof (pager.onPageChange) == "function") {
                pager.onPageChange(current);
            }
        });
        //上一页
        this.$wrap.on("click", "a.prevPage", function () {
            var current = parseInt(pager.$wrap.children("span.current").text());
            pager.render(pager.pageCount, current - 1);
            if (typeof (pager.onPageChange) == "function") {
                pager.onPageChange(current);
            }
        });
        //下一页
        this.$wrap.on("click", "a.nextPage", function () {
            var current = parseInt(pager.$wrap.children("span.current").text());
            pager.render(pager.pageCount, current + 1);
            if (typeof (pager.onPageChange) == "function") {
                pager.onPageChange(current);
            }
        });
    }

    dw.Pager = Pager;
}('Pager', dw));

(function (dwName, dw) {

    function DataGrid($table, params) {
        this.name = dwName;
        this.$table = $table;         //表格对象
        this.url = $table.data('url');       //加载数据的url
        this.pageSize = $table.data('page-size') || 10;  // 每页大小
        this.pageIndex = $table.data('page-index') || 1; //当前页码
        this.columns = []; //列数据
        this.params = {}; //查询参数
        this.pager = null;//分页控件
        this.isSearch = false;
        var $this = this;

        $table.find('thead>tr>th').each(function () {
            var $th = $(this);
            var field = $th.data('field');
            if (field == "$index") {
                if (!$th.attr("style") || $th.attr("style").indexOf("width") < 0) {
                    $th.css("width", "20px");
                }
            }
            $this.columns.push({ field: field, formatter: $th.data('formatter'), format: $th.data('format'), url: $th.data('url') });
        });
        //分页
        $table.append('<tfoot><tr><td colspan="' + this.columns.length + '" class="page"></td></tr></tfoot>');
        this.load(params);
    }

    //加载数据
    DataGrid.prototype.load = function (params) {
        params = params || {};
        this.params = params;
        params.pageIndex = this.pageIndex;
        params.pageSize = this.pageSize;
        var $this = this;
        $.post(this.url, params, function (data) {
            $this.render(data);
        });
    };
    DataGrid.prototype.search = function (params) {
        this.pageIndex = 1;
        this.isSearch = true;
        this.load(params);
    }

    DataGrid.prototype.render = function (data) {
        var $datagrid = this;

        var html_arr = [];
        html_arr.push('<tbody>');

        for (var i = 0; i < data.List.length; i++) {
            var item = data.List[i];
            html_arr.push('<tr>');

            for (var j = 0; j < $datagrid.columns.length; j++) {
                var column = this.columns[j];
                html_arr.push('<td>');
                if (column.field == "$index") {
                    html_arr.push(this.pageSize * (this.pageIndex - 1) + i + 1);
                } else {
                    var renderValue = getRenderValue(item, column);
                    html_arr.push(renderValue);
                }
                html_arr.push('</td>');
            }
            html_arr.push('</tr>');
        }
        html_arr.push('</tbody>');
        var tbody = $datagrid.$table.find('tbody');
        if (tbody.length > 0) {
            tbody.replaceWith(html_arr.join(''));
            if (this.isSearch) {
                $datagrid.pager.render(data.PageCount, data.PageIndex);
                this.isSearch = false;
            }
        } else {
            $datagrid.$table.append(html_arr.join(''));
            //分页

            this.pager = new dw.Pager($datagrid.$table.find('.page'), data.PageCount, data.PageIndex, function (num) {
                $datagrid.pageIndex = num;
                $datagrid.load($datagrid.params);
            })
        }
    };

    function urlMapping(id, list) {
        for (var i = 0; i < list.length; i++) {
            var item = list[i];
            if (id == item.ID) {
                return item.Name;
            }
        }
        return '';
    }

    function getRenderValue(item, column) {
        var val = item[column.field];
        if (column.formatter) {
            return eval(column.formatter + '(val,item)');
        }
        else if (column.url) {
            var list = dw.getCache(column.url);
            return urlMapping(val, list);
        }
        else {
            if (typeof (val) === "string") {
                if (/Date\([\d+]+\)/.test(val)) {
                    var date = eval(val.replace(/\/Date\((\d+)\)\//gi, "new Date($1)"));
                    val = dw.dateFormat(date, column.format || 'yyyy-MM-dd hh:mm');
                    return val;
                }
            }
            return val;
        }
    }

    dw.DataGrid = DataGrid;

}('DataGrid', dw));

(function (dwName, dw) {
    function Select($select, params) {
        this.name = dwName;
        var args = $.extend({
            value: undefined,
            onInit: undefined,
            hasDefault: true,
            defaultText: '请选择',
            defaultValue: ''
        }, params);

        this.$select = $select;
        var url = $select.data('url');

        var list = dw.getCache(url);
        fillSelect(list);

        //[{ID:id,Name:name}]
        function fillSelect(list) {
            var htmlArr = [];
            if (args.hasDefault) {
                htmlArr.push('<option value="' + args.defaultValue + '">' + args.defaultText + '</option>');
            }
            for (var i = 0; i < list.length; i++) {
                var item = list[i];
                htmlArr.push('<option value="' + item.ID + '">' + item.Name + '</option>');
            }
            $select.html(htmlArr.join(''));
            if (args.value !== undefined) {
                $select.val(args.value);
            }
            if (args.onInit && typeof (args.onInit) === "function") {
                args.onInit(list);
            }
        }
    }

    dw.Select = Select;
}('Select', dw));